package models_main

import (
	"fmt"
	"longmen/server/config/global"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql/models"
	"strings"
)

// IpStats 每日IP统计
type IpStats struct {
	Id           int64  `json:"id"`            // ID
	Date         string `json:"date"`          // 日期
	IpCount      int64  `json:"ip_count"`      // IP数量
	DeviceCount  int64  `json:"device_count"`  // 设备数量
	IosCount     int64  `json:"ios_count"`     // IOS数量
	AndroidCount int64  `json:"android_count"` // Android数量
	PcCount      int64  `json:"pc_count"`      // PC数量
	H5Count      int64  `json:"h5_count"`      // H5数量
}

func (i IpStats) TableName() string {
	return fmt.Sprintf("%sip_stats", models.Prefix)
}

func (i IpStats) ReadTodayIpCount() int64 {
	rdc := global.GetRds()
	i2, err := rdc.Get(fmt.Sprintf(_const.GlobalCount, i.Date)).Int64()
	if err != nil {
		return 0
	}
	return i2
}

func GenTodayIpStats(date string) IpStats {
	instance := IpStats{
		Date: date,
	}
	instance.IpCount = instance.ReadTodayIpCount()
	return instance
}

func (i *IpStats) GetPlatformCount(date string) error {

	result, err := global.GetRds().HGetAll(fmt.Sprintf("device_info:%s", date)).Result()
	if err != nil {
		return err
	}

	m := make(map[string]int64)
	for _, ipAndPlatform := range result {
		v := strings.Split(ipAndPlatform, ";")
		if len(v) < 2 {
			continue
		}
		m[v[1]] = m[v[1]] + 1
	}

	i.PcCount = m["0"]
	i.IosCount = m["1"]
	i.AndroidCount = m["2"]
	i.H5Count = m["3"]

	// 注册来源  web-0; ios-1; android-2 3-H5

	return nil
}
